local BaseData = require("data.base.BaseData")
local ItemsData = class("ItemsData", BaseData)
local ItemUnitData = require("data.ItemUnitData")
local StoreConst = require("const.StoreConst")

function ItemsData:ctor()
    ItemsData.super.ctor(self)
    self._itemsList = {}
end

function ItemsData:init()
    self:_initData()
end

function ItemsData:_initData()
    local items = G_StoreManager:getDataList(StoreConst.ITEMS)
    for i = 1, #items do
        self:_setUnitData(items[i])
    end
end

function ItemsData:getItemNum(id)
    local unit = self._itemsList["k_" .. id]
    if unit then
        return unit:getNum()
    end
    return 0
end

function ItemsData:save()
    local result = {}
    for _, unit in pairs(self._itemsList) do
        local param = unit:getPureData()
        if param.num > 0 then
            table.insert(result, param)
        end
    end
    G_StoreManager:setDataList(StoreConst.ITEMS, result)
end

function ItemsData:_setUnitData(data, isAdd)
    local unit = self._itemsList["k_" .. data.id]
    if not unit then
        unit = ItemUnitData.new()
        self._itemsList["k_" .. data.id] = unit
    end
    unit:update(data, isAdd)
end

function ItemsData:addData(id, num, isAdd)
    local data = {}
    data.id = id
    data.num = num or 0
    printDebug("ItemsData:addData")
    self:_setUnitData(data, isAdd)
end

function ItemsData:getItemList()
    local result = {}
    for _, unit in pairs(self._itemsList) do
        if unit:getNum() > 0 then
            table.insert(result, unit)
        end
    end
    return result
end

function ItemsData:useItem(id, num)
    local unit = self._itemsList["k_" .. id]
    if unit then
        local curNum = unit:getNum()
        if curNum >= num then
            local newNum = curNum - num
            unit:setNum(newNum)
            return true
        end
    end
    return false
end

return ItemsData
